package com.wang.cotroller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.wang.pojo.User;
import com.wang.utils.JsonUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
//@RestController  不使用视图解析器 ，与下面的@ResponseBody用法一样
public class json {


    //转化普通的字符串
    @RequestMapping(value = "/j1" ,produces = "application/json;charset=utf-8")
    @ResponseBody //不使用视图解析器，直接在localhost8080://项目名/j1 显示返回的字符串
    public String json1() throws JsonProcessingException {

        //jackson的对象
        ObjectMapper mapper=new ObjectMapper();
        //User对象
        User user=new User(1,"旁顾",35);

        //转化成json格式
        mapper.writeValueAsString(user);

        return mapper.writeValueAsString(user);
    }

    //将时间转成json格式
    @RequestMapping(value = "/j2" ,produces = "application/json;charset=utf-8")
    @ResponseBody //不使用视图解析器，直接在localhost8080://项目名/j2 显示返回的字符串
    public String json2() throws JsonProcessingException {

        //jackson的对象
        ObjectMapper mapper=new ObjectMapper();

        Date date=new Date();

        //改变时间格式
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        return  mapper.writeValueAsString(simpleDateFormat.format(date));
    }
    @RequestMapping(value = "/j3" ,produces = "application/json;charset=utf-8")
    @ResponseBody //不使用视图解析器，直接在localhost8080://项目名/j3 显示返回的字符串
    public String json3() throws JsonProcessingException {

        //jackson的对象
        ObjectMapper mapper=new ObjectMapper();

        //不使用时间戳的方式  将使用时间戳改为false
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

        Date date=new Date();

        //改变时间格式
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        mapper.setDateFormat(simpleDateFormat);


        return  mapper.writeValueAsString(date);
    }


    @RequestMapping(value = "/j4" ,produces = "application/json;charset=utf-8")
    @ResponseBody //不使用视图解析器，直接在localhost8080://项目名/j3 显示返回的字符串
    public String json4() throws JsonProcessingException {

        User user1 = new User(1, "网二", 34);
        User user2 = new User(2, "沙雕", 43);
        User user3 = new User(3, "迪迦", 56);
        User user4 = new User(4, "雷猴", 67);
        List<User> list = new ArrayList<User>();
        list.add(user1);
        list.add(user2);
        list.add(user3);
        list.add(user4);
        return JsonUtil.getJson(list);
    }


}
